package top.retain;


import java.util.LinkedList;

/**
 * @author ivorfan
 * @date 2021/8/11 21:46
 */
public class ReverseK {
    static class ListNode{
        int key;
        ListNode next;
        public ListNode(){};
        public ListNode(int key) {
            this.key = key;
        }
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next =node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        ReverseK k = new ReverseK();
        k.reverseKGroup(node1,2);
        System.out.println();
    }
    ListNode newHead;
    ListNode root;
    private ListNode reverseKGroup(ListNode head, int k) {
        int size = 0;
        LinkedList<ListNode> list = new LinkedList<>();
        ListNode pHead = head;
        int h = k;
        while( head != null) {
            if (--h == 0) {
                list.offer(head);
                h = k;
            }
            size++;
            head = head.next;
        }
        // 循环次数
        int count = (size / k) - 1 ;
        ListNode preLast = reverse(null, pHead, k - 1);
        root = list.poll();
        while (count > 0 ) {
            newHead = list.poll();
            preLast = reverse(preLast, newHead, k - 1);
            count --;
        }
        return root;
    }
    // pre:1 head:2 root:head.next:3
    public ListNode reverse(ListNode pre, ListNode head, int k) {
        if (k == 0) {
            return head;
        }
        ListNode root = reverse(head, head.next, k-1);
        root.next = head;
        head.next = pre;
        return head;
    }
}
